import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';

import { pageRecords } from '@/interface/pageInterface';
import { config } from '@/config/index';
import { RoleService } from '../roleService';

import { RoleEntity } from '@/entity/role.entity';
const { page } = config;

@Injectable()
export class RoleServiceImpl implements RoleService {
  constructor(
    @InjectRepository(RoleEntity)
    private roleRepository: Repository<RoleEntity>,
  ) {}
  /**
   * 判断角色名称是否存在
   * @param role_name
   */
  async isExistRole(role_name: string): Promise<{ isExistRole: boolean }> {
    const isExist = await this.roleRepository.findOne({ where: { role_name } });
    if (isExist) {
      throw new BadRequestException('参数错误 : 角色已存在');
    }
    return { isExistRole: false };
  }
  /**
   *  创建角色
   * @param RoleInsertDto
   */
  async insert(RoleInsertDto): Promise<RoleEntity> {
    await this.isExistRole(RoleInsertDto.role_name);
    // isExistRole 如果有了会直接抛出错误，所以这里不用判断。
    return await this.roleRepository.save(RoleInsertDto);
  }

  /**
   * 删除角色
   * @param id
   */
  async delete(id): Promise<unknown> {
    const role = await this.find(id);
    if (!role) {
      throw new BadRequestException('角色不存在');
    }
    return await this.roleRepository.delete(id);
  }
  /**
   * 查找一个角色
   * @param id
   */
  async find(id): Promise<RoleEntity> {
    return this.roleRepository.findOne(id);
  }
  /**
   *
   * @param body
   */
  async list(query): Promise<pageRecords<RoleEntity>> {
    console.log(query);
    /**
     * pageSize : 显示几条
     * pageNumber: 页码 第几页
     */
    let { pageSize, pageNumber } = query;
    /*  
        skip:跳过几条：所以有公式：， take:显示几条
        注意：数据库分页没有0 页  用户界面也没有0 页的
     */
    const result = await this.roleRepository.findAndCount({
      skip: pageSize * (pageNumber - 1) ?? page.pageSize,
      take: pageSize ?? page.pageSize,
    });
    const records = result[0];
    const total = result[1];
    return { total, records };
  }

  async update(body) {
    const { id, role_name } = body;
    const role = await this.find(id);
    if (!role) {
      throw new BadRequestException('角色不存在');
    }
    return await this.roleRepository.update(id, {
      role_name,
    });
    /* TODO 返回结果，想下要不要就这样返回
    "generatedMaps": [],
    "raw": [],
    "affected": 1
    */
  }
}
